package top.purity.server.gateway.permission;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.purity.framework.common.GlobalConstant;
import top.purity.server.gateway.feign.input.UserFeign;
import top.purity.server.gateway.feign.input.dto.PermissionDTO;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @Author lmh
 * @Description sa token 权限处理器
 * @CreateTime 2023-09-25 15:19
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class StpPermissionInterceptor implements StpInterface {

    private final UserFeign userFeign;

    private static final ExecutorService POOL = Executors.newSingleThreadExecutor();

    @Override
    public List<String> getPermissionList(Object o, String s) {
        if (ObjUtil.isNull(o)) {
            return null;
        }

        String loginId = (String) o;
        List<String> split = StrUtil.split(loginId, GlobalConstant.LOGIN_ID_SPLIT);
        Long userId = Long.valueOf(split.get(GlobalConstant.LOGIN_ID_INDEX_USER));
        Long tenantId = Long.valueOf(split.get(GlobalConstant.LOGIN_ID_INDEX_TENANT));

        // 异步回调，网关内部不允许使用同步请求调用
        // 获取当前用户拥有的权限
        try(POOL) {
            Future<List<PermissionDTO>> submit = POOL.submit(() -> userFeign.getPermission(userId, tenantId));
            List<PermissionDTO> permission = submit.get();
            if (CollUtil.isEmpty(permission)) {
                return null;
            }

            return permission.stream().map(PermissionDTO::getMenuCode).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取权限异常", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        return null;
    }
}
